﻿using Dapper;
using MediatR;
using MySql.Data.MySqlClient;
using System.Text;
using Warehouse.Api.Read.AGCation.Command;
using Warehouse.Api.Read.Dtos;
using Warehouse.Domian.Model;
using Warehouse.ErrorCode;
using Warehouse.Infrastructrue.Implenment;

namespace Warehouse.Api.Read.AGCation.Hanlder
{
    public class GetInventoryCommandHanlder : IRequestHandler<GetInventoryCommand, ApiPaging<InventoryDto>>
    {
        DbContext db;
        public readonly IBaseRepostity<InventoryModel> baseRepostity;

        public GetInventoryCommandHanlder(DbContext db, IBaseRepostity<InventoryModel> baseRepostity)
        {
            this.db = db;
            this.baseRepostity = baseRepostity;
        }
        /// <summary>
        /// 获取库存盘点信息的列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>

        public async Task<ApiPaging<InventoryDto>> Handle(GetInventoryCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<InventoryDto> result = new ApiPaging<InventoryDto>();
            try
            {
                var countsql = new StringBuilder();
                var sqlbuilder = new StringBuilder();
                sqlbuilder.Append(@" 																				SELECT 
																				inven.InventiryId,
                                                    inven.TrackingNumber,
    inven.WarehouseName,
    inven.StartTime,
    inven.EndTime,
    inven.Satate,
    inven.InventoryName,
    inven.Inventorycount,
    inven.Inventorytota,
    inven.States,
    good.GoodName,
    good.Specification,
    good.Inventory,
    type.TypeName,
    res.ResultName
FROM 
                             inventorymodel inven 
                             JOIN 
                             warehousetypemodel type ON inven.TypeId = type.TypeId 
                              JOIN 
                              resultmodel res ON inven.ResultId = res.ResultId 
                              JOIN 
                            GoodsType good ON inven.GoodId = good.GoodId 
                           where inven.States =1 ");
                countsql.Append(@"SELECT count(inven.InventiryId)FROM inventorymodel inven
                                        JOIN warehousetypemodel type
                                         ON inven.TypeId = type.TypeId
                                        JOIN resultmodel res 
                                        ON inven.ResultId = res.ResultId
                                        WHERE inven.States =1 ");
                //实例话Deppand
                var parmenters = new DynamicParameters();
                // 添加 TrackingNumber 条件
                if (!string.IsNullOrWhiteSpace(request.TrackingNumber))
                {
                    sqlbuilder.Append(" AND inven.TrackingNumber LIKE @TrackingNumber ");
                    parmenters.Add("TrackingNumber", $"%{request.TrackingNumber}%");
                }
                //添加 WarehouseName 条件
                if (!string.IsNullOrWhiteSpace(request.WarehouseName))
                {
                    sqlbuilder.Append(" AND inven.WarehouseName LIKE @WarehouseName ");
                    parmenters.Add("WarehouseName", $"%{request.WarehouseName}%");
                }
                //添加类型条件
                if (request.ResultId != null)
                {
                    sqlbuilder.Append(" AND res.ResultId = @ResultId ");
                    parmenters.Add("ResultId", request.ResultId);
                }
                //添加结果条件
                if (request.TypeId != null)
                {
                    sqlbuilder.Append(" AND type.TypeId = @TypeId ");
                    parmenters.Add("TypeId", request.TypeId);
                }
                sqlbuilder.Append("limit @pagesize offset @offset");
                parmenters.Add("pagesize", request.PageSize);
                parmenters.Add("offset", (request.PageIndex - 1) * request.PageSize);
                using var conn = new MySqlConnection("server=120.27.210.76;uid=wms_user;pwd=MyPassword123!;database=warehousemanagement;CharSet=utf8mb4;");
                await conn.OpenAsync(cancellationToken);
                var data = await conn.QueryAsync<InventoryDto>(sqlbuilder.ToString(), parmenters);
                var total = await conn.ExecuteScalarAsync<int>(countsql.ToString(), parmenters);
                if (request.PageSize <= 0)
                {
                    result.Msg = "显示数量不能小于等于0";
                    result.Code = ApiEume.Error;
                    return result;
                }
                result.Msg = "显示成功";
                result.Code = ApiEume.Success;
                result.PageData = data.ToList();
                result.TotaCount = total;
                result.PageCount = (int)Math.Ceiling((double)total / request.PageSize);

            }
            catch (Exception ex)
            {

            }
            return result;
        }
    }
}
